package controller;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;

import util.DAOException;
import domain.Contact;
import domain.itf.IDAOContact;

/**
 * Controller implementation for Feed the database with spring.
 */
@Controller
@RequestMapping("/FeedDatabase")
public class FeedDatabaseController {
	
	@Autowired
    ServletContext servletContext;
	
	private static boolean alreadyFeed = false;

	@RequestMapping(method = RequestMethod.GET)
	protected ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("main");
		
		try {
			if (!alreadyFeed) {
				alreadyFeed = true;
				// get the objects examples
				ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
				Contact contact = (Contact) context.getBean("contactExample");
				Contact contact2 = (Contact) context.getBean("contactExample2");
				Contact contact3 = (Contact) context.getBean("contactExample3");
				IDAOContact daoContact = (IDAOContact) context.getBean("DAOContact");

				daoContact.addContact(contact);
				daoContact.addContact(contact2);
				daoContact.addContact(contact3);
				
				view.addObject("messageInfo", "You have successfull fed the database :-).");
			} else {
				view.addObject("messageInfo", "You have already fed the database ;-).");
			}
		} catch (DAOException e) {
			view.addObject("messageError", "Sorry, impossible to feed the database :-(");
		}
		
		return view;
	}
}
